package com.molyfun.parents.utils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.text.TextPaint;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitmapUtil {

	private static final int MAX_IMAGE_SIZE = 256 ;

	//保存图片到本地
	public static void saveBitmap(Bitmap bm,File targetFile) throws IOException{
		if(!targetFile.getParentFile().exists()){
			targetFile.getParentFile().mkdirs();
		}
		FileOutputStream fos=new FileOutputStream(targetFile);
		bm.compress(CompressFormat.JPEG,95, fos);
		fos.close();
	}

	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	//根据路径加载图片
	public static Bitmap loadBitmap(String path){

		File targetFile=new File(path);
		if(!targetFile.exists())return null;
		return BitmapFactory.decodeFile(path);
	}

	public static Bitmap decodeSampledBitmapFromFile(String filepath,
													 int reqWidth, int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filepath, options);

		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filepath, options);
	}

	public static Bitmap decodeSampledBitmapFromBitmap(Bitmap bitmap,
													   int reqWidth, int reqHeight) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
		byte[] data = baos.toByteArray();

		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeByteArray(data, 0, data.length, options);
	}

	//计算图片的缩放值
	private static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		System.out.println("filePath--reqWidth--->" + reqWidth + "reqHeight--->" + reqHeight);

		if (height>reqHeight || width>reqWidth) {
			final int heightRatio = Math.round((float) height/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio<widthRatio ? heightRatio : widthRatio;
		}
		return inSampleSize;
	}


	public static void compressBitmap(String filePath, String destPath) throws IOException {
		System.out.println("filePath--->" + filePath);
		if(!TextUtils.isEmpty(filePath)){
			int degree = getBitmapDegree(filePath);
			Bitmap bitmap = rotateBitmapByDegree(getSmallBitmap(filePath), degree);

			saveBitmap(bitmap, new File(destPath));
			if(bitmap != null && !bitmap.isRecycled()){
				bitmap.recycle();
			}
		}
	}

	/**
	 * 读取图片的旋转的角度
	 *
	 * @param path
	 *            图片绝对路径
	 * @return 图片的旋转角度
	 */
	private static int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * * 将图片按照某个角度进行旋转
	 *
	 * @param bm
	 *            需要旋转的图片
	 * @param degree
	 *            旋转角度
	 * @return 旋转后的图片
	 */
	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;

		// 根据旋转角度，生成旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图片
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
		} catch (OutOfMemoryError e) {
		}
		if (returnBm == null) {
			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;
	}

	// 根据路径获得图片并压缩，返回bitmap用于显示
	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		options.inPreferredConfig = Config.RGB_565;
		BitmapFactory.decodeFile(filePath, options);
		options.inJustDecodeBounds = false;
		options.inSampleSize = calculateInSampleSize(options, 480, 800);

		return BitmapFactory.decodeFile(filePath, options);
	}
	//创建图片存储目录
	public static File getPhotoDir(){
		File file=new File(FileUtils.IMAGE_PAYH);
		if(!file.exists()){
			file.mkdirs();
		}
		return file;
	}
	// 加水印 也可以加文字
	public static Bitmap watermarkBitmap(Bitmap src,String... titles) {
		if (src == null) {
			return null;
		}
		int w = src.getWidth();
		int h = src.getHeight();
		//需要处理图片太大造成的内存超过的问题,这里我的图片很小所以不写相应代码了
		Bitmap newb= Bitmap.createBitmap(w, h, Config.RGB_565);// 创建一个新的和SRC长度宽度一样的位图
		Canvas cv = new Canvas(newb);
		cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
		Paint paint=new Paint();
//        //加入图片
//        if (watermark != null) {
//            int ww = watermark.getWidth();
//            int wh = watermark.getHeight();
//            paint.setAlpha(50);
//            cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, paint);// 在src的右下角画入水印            
//        }
		//加底边背景色
		paint.setColor(Color.TRANSPARENT);
		Rect r=new Rect(0, h-160, w, h);
		cv.drawRect(r, paint);
		//加入文字
		if(titles!=null)
		{
			String familyName ="宋体";
			Typeface font = Typeface.create(familyName,Typeface.BOLD);
			TextPaint textPaint=new TextPaint();
			textPaint.setColor(Color.WHITE);
			textPaint.setTypeface(font);
			textPaint.setTextSize(18);
			//这里是自动换行的
//            StaticLayout layout = new StaticLayout(title,textPaint,w,Alignment.ALIGN_NORMAL,1.0F,0.0F,true);
//            layout.draw(cv);
			//文字位置
			for(int i=0;i<titles.length;i++){
				cv.drawText(titles[i],140,h-120+i*32,textPaint);
			}
		}
		cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		cv.restore();// 存储
		return newb;
	}


}
